#解决ssh到一台机器远程执行命令的方法， 限定从linux系统发起， 到linux使用，windows发起会报错
import pexpect

PROMPT = ['# ', '>>> ', '> ','\$ ']

def send_command(child, cmd):
    #发送命令
    child.sendline(cmd)
    child.expect(PROMPT)
    #返回命令执行结果
    print (child.before)

    #连接目标SSH服务器
    #感觉很类似你手工登录SSH一样流程，一样的提示
    #expect函数是在屏幕上打印提示消息
def connect(user, host, password):
    ssh_newkey = 'Are you sure you want to continue connecting'
    connStr = 'ssh ' + user + '@' + host
    #生成一个 spawn 类的对象
    child = pexpect.spawn(connStr)
    ret = child.expect([pexpect.TIMEOUT, ssh_newkey,\
                        '[P|p]assword:'])
    #expect返回为0表示错误
    #成功的话就发送一个yes消息
    if ret == 0:
        print ('[-] Error Connecting')
        return

    if ret == 1:
        child.sendline('yes')
        ret = child.expect([pexpect.TIMEOUT, \
                            '[P|p]assword:'])
        if ret == 0:
            print ('[-] Error Connecting')
            return

    child.sendline(password)
    child.expect(PROMPT)
    return child


def main():
    host = 'x.x.x.x'
    user = '用户名'
    password = '我是密码'

    child = connect(user, host, password)
    send_command(child, 'cat /etc/shadow | grep root')

if __name__ == '__main__':
    main()
